package io.gitee.hefren.hhmq.bean;

import java.util.Iterator;
import java.util.Objects;

/**
 * 队列：FIFO 先进先出
 * @Date 2024/7/19
 * @Author lifei
 */
public class HhQueue<Item> implements Iterable<Item> {

    // 链表的第一个节点
    private Node first;
    // 链表的最后一个节点
    private Node last;
    private int N;

    // 用链表的形式来实现队列
    private class Node {
        Item item;
        Node next;

        public Node(Item item) {
            this.item = item;
        }
    }

    // 向队列中插入数据
    public void enqueue(Item item) {
        Node oldLast = last;
        last = new Node(item);
        if (isEmpty()) {
            first = last;
        } else {
            oldLast.next = last;
        }
        N++;
    }

    // 弹出一个元素
    public Item dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("HhQueue is empty");
        }
        Item item = first.item;
        first = first.next;
        N--;
        if (isEmpty()) {
            last = null;
        }
        return item;
    }

    // 队列的大小
    public int size() {
        return N;
    }

    // 判断队列是否为空
    public boolean isEmpty() {
        return N==0;
    }

    @Override
    public Iterator<Item> iterator() {
        return new HhQueueIterator();
    }


    private class HhQueueIterator implements Iterator<Item> {

        private Node current = first;

        @Override
        public boolean hasNext() {
            return Objects.nonNull(current);
        }

        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
}
